package com.cwx.web.admin;

import com.alibaba.fastjson.JSONObject;
import com.cwx.pojo.Blog;
import com.cwx.pojo.User;
import com.cwx.service.BlogService;
import com.cwx.service.TagsService;
import com.cwx.service.TypeService;
import com.cwx.vo.BlogQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/admin")
public class BlogController {

    @Autowired
    private TagsService tagsService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @GetMapping("/blogs")
    public String blog(@PageableDefault(size = 4,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                       Model model, BlogQuery blog){
        model.addAttribute("page",blogService.listBlog(pageable,blog));
        model.addAttribute("types",typeService.listType());

        return "admin/blogs";
    }

    //博客列表页面的查询请求
    @PostMapping("/blogs/search")
    public String search(@PageableDefault(size = 2,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                       Model model, BlogQuery blog){
        Page<Blog> page = blogService.listBlog(pageable, blog);
        model.addAttribute("page",page);
            return "admin/blogs :: blogList";  //返回admin下面的的问价夹下面的一个网页的一个片段
    }

    //跳转到添加博客页面
    @GetMapping("/blogs/input")
    public String input(Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagsService.listTag());
        model.addAttribute("blog",new Blog());
        return "admin/blogs-input";
    }


    //跳转到编辑博客页面
    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable Long id, Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagsService.listTag());
        Blog blog = blogService.getBlog(id);
        blog.init();
//        System.out.println(blog.getTags());
//        System.out.println(blog.getTagIds());
        model.addAttribute("blog",blog);
        return "admin/blogs-input";
    }

    //添加博客请求
    @PostMapping("/blogs")
    public String post(Blog blog, RedirectAttributes attributes, HttpSession session){
        System.out.println(blog.getTagIds());
        //从session中获取博客的用户
        blog.setUser((User) session.getAttribute("user"));
        //前端页面提交的请求分类的名字  是type.id   在我们的controller中  会自动封城成为一个type
        //在里面new了一个Type  然后给他setId(type.id)   所以我们可以直接调用到这个type
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagsService.listTag(blog.getTagIds()));


        //添加博客
        Blog b = blogService.saveBlog(blog);
        if (b == null){
            attributes.addFlashAttribute("message","操作失败");
        }else {
            attributes.addFlashAttribute("message","操作成功");
        }
        //添加完成之后  重定向到博客列表页面
        return "redirect:/admin/blogs";
    }

    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes){
        blogService.deleteBlog(id);
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/blogs";
    }


    //富文本编辑上传图片的功能
    @PostMapping("/file/upload")
    @ResponseBody
    public JSONObject upload(@RequestParam(value = "editormd-image-file",required = true) MultipartFile file,
                              HttpServletRequest request) throws IOException {
        //上传图片保存设置

        //获得Springboot当前项目路径：System.getProperty("user.dir")
        //获得当前目录下面的upload目录
        String path = System.getProperty("user.dir")+"/upload/";

        //创建目录
        File realPath = new File(path);
        if(!realPath.exists()){
            realPath.mkdirs();//父级目录可以不存 连同父级一起创建  mkdir则父级目录必须存在
        }

        //上传文件的地址
        System.out.println("上传文件的地址" + realPath);

        // 解决文件名字问题，我们使用uuid
        String filename = "ct-" + UUID.randomUUID().toString().replaceAll("-","");
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(new File(realPath + "/" + filename));

        // 给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url","/upload/"+ filename);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;
    }


}
